<template>
  <div class="login-container">
        <!-- 顶部欢迎文本 -->
        <div class="welcome-area">
          <div class="welcome-text">您好，<br>欢迎登录云境平台</div>
          <div v-if="isRedirecting || 1 == 1" class="oa-redirect-notice">
			<span @click="handleOARedirect">点击跳转到OA登录系统...</span>
          </div>
        </div>

        <!-- 登录内容区域 -->
        <div class="login-content">
          <div class="login-tabs">
            <div
              :class="['tab-item', { 'active': loginWay === 1 }]"
              @click="loginWay = 1"
            >密码登录</div>
            <div
              :class="['tab-item', { 'active': loginWay === 2 }]"
              @click="loginWay = 2"
            >验证码登录</div>
          </div>

          <!-- 密码登录 -->
          <div v-if="loginWay === 1" class="form-container">
            <van-cell-group :border="false">
              <van-field
                v-model="userName"
                placeholder="请输入用户名"
                class="custom-field"
                :border="false"
              >
                <template #left-icon>
                  <van-icon name="contact" class="field-icon" />
                </template>
              </van-field>

              <van-field
                v-model="password"
                placeholder="请输入密码"
                :type="showPassword ? 'text' : 'password'"
                class="custom-field"
                :border="false"
              >
                <template #left-icon>
                  <van-icon name="lock" class="field-icon" />
                </template>
                <template #right-icon>
                  <van-icon
                    :name="showPassword ? 'eye-o' : 'closed-eye'"
                    class="field-icon eye-icon"
                    @click="showPassword = !showPassword"
                  />
                </template>
              </van-field>
            </van-cell-group>

            <div class="forgot-password">
              <span @click="handleForgotPassword">忘记密码</span>
            </div>

            <div class="button-con">
              <van-button
                type="primary"
                block
                class="login-btn"
                @click="onLogin"
              >登录</van-button>
            </div>
          </div>

          <!-- 验证码登录 -->
          <div v-else class="form-container">
            <van-cell-group :border="false">
              <van-field
                v-model="phoneNo"
                placeholder="请输入手机号"
				maxlength="11"
                class="custom-field"
                :border="false"
              >
                <template #left-icon>
                  <van-icon name="phone-o" class="field-icon" />
                </template>
              </van-field>

              <van-field
                v-model="smsCode"
                placeholder="请输入短信验证码"
                class="custom-field"
                :border="false"
              >
                <template #left-icon>
                  <van-icon name="comment-o" class="field-icon" />
                </template>
                <van-button
                  slot="button"
                  size="small"
                  plain
                  type="primary"
                  class="send-btn"
                  @click="onSMSSend"
                  :disabled="!isSendSMSEnable"
                >
                  {{ getSendBtnText }}
                </van-button>
              </van-field>
            </van-cell-group>


            <div class="button-con">
              <van-button
                type="primary"
                block
                class="login-btn"
                @click="onSMSLogin"
              >登录</van-button>
            </div>
          </div>

          <div class="register-area">
            <span class="register-label">没有账号？<span class="register-link" @click="handleRegister">立即注册</span></span>
          </div>

          <div class="agreement-area">
            <van-checkbox v-model="agreementChecked" icon-size="18px" checked-color="#26B1A1"></van-checkbox>
            <span class="agreement-label">我已阅读并同意</span>
            <span class="agreement-link" @click="showAgreement('service')">服务协议</span>
            <span>和</span>
            <span class="agreement-link" @click="showAgreement('privacy')">隐私政策</span>
          </div>
        </div>
    </div>
</template>

<script>
  import 'vant/lib/field/style/less';
  import { Toast } from 'vant';
  import { Notify } from 'vant';
  import { mapActions } from "vuex"
  import router from '@/router.js'
  import { isMobile } from '@/util/validate.js'
  import { getDynamicRoute } from '@/util/constants.js'
  import { postAction } from "@/api";

  export default {
    name: "login-page",
    data() {
      return {
        userName: '',
        password: '',
        phoneNo: '',
        smsCode: '',
        showPassword: false,
        loginWay: 1, // 1: 密码登录, 2: 验证码登录
        smsCountDown: 0,
        smsCountInterval: null,
        agreementChecked: true,
		isRedirecting: false // 添加重定向状态
      };
    },
    computed: {
      isSendSMSEnable() {
        return this.smsCountDown <= 0 && this.phoneNo.length == 11;
      },
      getSendBtnText() {
        if (this.smsCountDown > 0) {
          return this.smsCountDown + '秒后发送';
        } else {
          return '发送验证码';
        }
      }
    },
	mounted(){
      //this.handleOARedirect();
	},
    beforeDestroy() {
      if (this.smsCountInterval) {
        clearInterval(this.smsCountInterval);
      }
    },
    methods: {
      ...mapActions([ "mLogin","PhoneLogin" ]),
      onLogin(){
        if(!this.userName || this.userName.length==0){
          Toast('请填写用户名');
          return;
        }
        if(!this.password || this.password.length==0){
          Toast('请填写密码');
          return;
        }
        if (!this.agreementChecked) {
          Toast('请阅读并同意服务协议和隐私政策');
          return;
        }

        let loginParams = {
          username:this.userName,
          password:this.password
        }
        this.mLogin(loginParams).then((res) => {
          if(res.success){

            router.$addRoutes(getDynamicRoute())
            Notify({ type: 'success', message: '登录成功!' });
			this.$router.push({ path: "/" });
			console.log("store",this.$store.getters)

          }else{
            Toast.fail(res.result.message);
          }
        }).catch((err) => {
          let msg = ((err.response || {}).data || {}).message || err.message || "请求出现错误，请稍后再试"
          Toast.fail(msg);
        });
      },
      onSMSSend() {
        let smsParams = {};
        smsParams.mobile=this.phoneNo;
        smsParams.smsmode="0";
        postAction("/sys/sms",smsParams).then(res=>{
          if(res.success){
            this.smsCountDown = 60;
            this.startSMSTimer();
          }else{
            this.smsCountDown = 0;
            Toast.fail(res.message);
          }
        });
      },
      startSMSTimer() {
        this.smsCountInterval = setInterval(() => {
          this.smsCountDown--;
          if (this.smsCountDown <= 0) {
            clearInterval(this.smsCountInterval);
          }
        }, 1000);
      },
      onSMSLogin() {
        if(!this.phoneNo || this.phoneNo.length!=11 || !isMobile(this.phoneNo)){
          Toast('请填写正确手机号');
          return;
        }
        if(!this.smsCode || this.smsCode.length==0){
          Toast('请填短信验证码');
          return;
        }
        if (!this.agreementChecked) {
          Toast('请阅读并同意服务协议和隐私政策');
          return;
        }

        let loginParams = {
          mobile:this.phoneNo,
          captcha:this.smsCode
        };
        this.PhoneLogin(loginParams).then((res) => {
          if(res.success){
            router.$addRoutes(getDynamicRoute())
            Notify({ type: 'success', message: '登录成功!' });
            this.$router.push({ path: "/" });
          }else{
            Toast.fail(res.result.message);
          }
        }).catch((err) => {
          let msg = ((err.response || {}).data || {}).message || err.message || "请求出现错误，请稍后再试"
          Toast.fail(msg);
        });
      },
      handleForgotPassword() {
        Toast('请通过绑定的手机号或邮箱找回密码');
      },
      handleRegister() {
        Toast('请前往云镜平台官网完成注册');
      },
      showAgreement(type) {
        const title = type === 'service' ? '服务协议' : '隐私政策';
        Toast(`查看${title}`);
      },
      handleOARedirect() {
		// 检查URL参数，避免无限重定向
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('oa_callback') || urlParams.has('error')) return;

		// 检查是否已登录
		if (this.$store.getters.token) {
          this.$router.push({ path: "/main/home" });
          return;
		}

		this.isRedirecting = true;

		// 从环境变量获取配置
		const oaBaseUrl = window._CONFIG['authURL'];
		const clientId =  'eb728e3137ca33e6';

		console.log(window.location.origin)

		// 构建回调URL（当前域名+OA回调路由）
		const redirectUri = encodeURIComponent(
          `${window.location.origin}/oa-callback`
		);

		console.log('回调URL:',redirectUri)
		// 构建OA认证URL
		const oaAuthUrl = `${oaBaseUrl}/oauth2.0/authorize?client_id=${clientId}&redirect_uri=${redirectUri}`;

		console.log('oaAuthUrl:',oaAuthUrl)
		// 重定向到OA登录
		window.location.href = oaAuthUrl;
      }
    },
  }
</script>

<style scoped>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      height: 100vh;
      overflow: hidden;
      position: relative;
    }

    .login-container {

      display: flex;
      flex-direction: column;
      height: 100%;
      padding: 0 0px;
      overflow-y: auto;
    }

    /* 顶部欢迎区域 */
    .welcome-area {
      background-image: url('/app/static/mobile/img/login/background2.png');
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      height: 27%;
      font-weight: bold;
      padding: 24px  30px;
      align-content: center;
    }

    .welcome-text {
      margin-left: 32px;
      font-size: 32px;
      color: #1a1a1a;
      line-height: 1.5;
    }

    /* 登录内容区域 */
    .login-content {
      flex: 1;
      width: 100%;
      background: #fff;
      border-radius: 20px 20px 0 0;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
      padding: 24px 24px 40px;
      position: relative;
      z-index: 10;
    }

    .login-tabs {
      display: flex;
      justify-content: left;
      padding-bottom: 15px;
      margin-bottom: 20px;
    }

    .tab-item {
      padding: 0 20px 0px;
      font-size: 18px;
      color: #8F959E;
      cursor: pointer;
      position: relative;
    }

    .tab-item.active {
      color: black;
      font-weight: bold;
    }

    .tab-item.active::after {
      content: '';
      position: absolute;
      bottom: -1px;
      left: 50%;
      transform: translateX(-50%);
      width: 24px;
      height: 3px;
      border-radius: 2px;
    }

    .form-container {
      margin-bottom: 20px;
    }

    .custom-field {
      color: #8F959E;
      font-size: 18px;
      max-height: 73px;
      padding: 24px 0;
      border-bottom: 1px solid #eee;
    }

    .field-icon {
      font-size: 24px;
      margin-right: 10px;
      color: #26B1A1;
    }

    .eye-icon {
      cursor: pointer;
      color: #8F959E;
    }

    .forgot-password {
      text-align: right;
      margin-top: 20px;
      font-size: 16px;
      color: #8F959E;
      cursor: pointer;
    }

    .login-btn {
      height: 62px;
      margin-top: 48px;
      border-radius: 32px;
      font-size: 18px;
      font-weight: 500;
      background: linear-gradient(90deg, #26B1A1 , #6FD0B3);
      border: none;
    }

    .send-btn {
      height: 36px;
      border-radius: 20px;
      font-size: 14px;
      padding: 0px 16px;
      background: linear-gradient(90deg, #26B1A1 , #6FD0B3);
      color: white !important;
      border: none;
    }

    .send-btn[disabled] {
      background: #f5f5f5;
      color: #8F959E !important;
    }

    .register-area {
      text-align: center;
      margin: 20px 0;
      font-size: 16px;
    }

	.register-label {
      color: #8F959E;
	}

    .register-link {
      color: #26B1A1;
      cursor: pointer;
      margin-left: 5px;
    }

    .agreement-area {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      color: #8F959E;
      margin-top: auto;
      position: absolute;
      bottom: 10%;
      right: 10%;
      left: 10%;
    }

	.agreement-label {
      margin-left: 8px;
	}
    .agreement-link {
      color: #26B1A1 ;
      cursor: pointer;
      margin: 0 4px;
    }

    /* 响应式调整 */
    @media (max-width: 1000px) {
      .welcome-area {
        padding: 40px 0 20px;

      }

      .welcome-text {
        font-size: 26px;
      }

      .login-content {
        padding: 20px 32px 30px;
      }

      .tab-item {
        padding: 0 36px 0px 0px;
      }
    }

    /* 添加OA重定向提示样式 */
    .oa-redirect-notice {
        margin-top: 80px;
        font-size: 16px;
		color: orange;
        background: rgba(38, 177, 161, 0.1);
        padding: 10px 15px;
        border-radius: 8px;
        text-align: center;
    }
</style>
